const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
const Minio = require('minio');

const minio = new Minio.Client({
  endPoint: 'ip',
  port: 80,
  useSSL: false,
  accessKey: 'accessKey',
  secretKey: 'secretKey'
})

const output = fs.createWriteStream(path.resolve(__dirname,'../pixelpiper.zip'));
const archive = archiver('zip', {
  zlib: { level: 9 }
});


output.on('close', function() {
  console.log(archive.pointer() + ' total bytes');
  console.log('archiver has been finalized and the output file descriptor has closed.');
  // 压缩完成后向 cdn 中传递压缩包
  const file = path.resolve(__dirname, '../pixelpiper.zip');
  fs.stat(file, function(error, stats) {
    if(error) {
      return console.error(error)
    }
    minio.putObject('cdn', 'pixelpiper.zip', fs.createReadStream(file), stats.size, 'application/zip', function(err, etag) {
      return console.log(err, etag) // err should be null
    })
  })
  
});

output.on('end', function() {
  console.log('Data has been drained');
});


archive.on('warning', function(err) {
  if (err.code === 'ENOENT') {
  } else {
    throw err;
  }
});

archive.on('error', function(err) {
  throw err;
});

archive.pipe(output);

archive.directory(path.resolve(__dirname, '../public'), false);

archive.finalize();